package services;

import domain.entities.Role;
import domain.entities.RoleDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;

@Service
public class RoleCRUDService implements CRUDService<Role>{

    private RoleDAO dao;

    public RoleCRUDService() {
    }

    @Autowired
    public RoleCRUDService(RoleDAO dao) {
        this.dao = dao;
    }

    public <V extends Criteria> List<Role> list(){
        return dao.findAll();
    }

    @Override
    public <V extends Criteria> List<Role> list(V criteria) {
        List<Role> list = list();
        Iterator<Role> it = list.iterator();
        while(it.hasNext()){
            if(!criteria.isIn(it.next())){
                it.remove();
            }
        }
        return list;
    }

    public List<Role> findStaffRole(){
        List<Role> roles = dao.findByProperty("bmsstaff",true);
        Collections.sort(roles);
        return roles;
    }

    public List<Role> findSiteRole(){
        List<Role> roles =  dao.findByProperty("siteStaff",true);
        Collections.sort(roles);
        return roles;
    }

    public Role getRoleById(int id){
        return dao.findById(id);
    }

    public void save(Role role){
        dao.attachDirty((domain.entities.Role) role);
    }

    public void delete(Role role) {
        dao.delete((domain.entities.Role) role);
    }


    public List<Role> findAll(){
        List<Role> roles = dao.findAll();
        Collections.sort(roles);
        return roles;
    }

}
